package com.taotao.async.task;

import com.google.common.base.Preconditions;
import com.taotao.async.task.exception.TaskContextException;
import com.taotao.async.task.result.ResultType;
import lombok.Getter;
import lombok.Setter;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 任务执行上下文
 */
@Getter
public class TaskExeContext {

    private final Long taskInstId;
    private final String param;
    private volatile Long startTime;
    private volatile Long endTime;
    @Setter
    private ResultType result;

    private ConcurrentHashMap<String, Object> varsMap = new ConcurrentHashMap<>();


    public TaskExeContext(Long taskInstId, String param) {
        this.taskInstId = taskInstId;
        this.param = param;
    }

    public void setVar(String key, Object value) {
        Preconditions.checkArgument(null != key);
        Preconditions.checkArgument(null != value);

        varsMap.put(key, value);
    }


    public Object getVar(String key) {
        Preconditions.checkArgument(null != key);
        return varsMap.get(key);
    }


    public synchronized void setStartTime() {
        if (null != startTime) {
            throw new TaskContextException(TaskContextException.CODE0 + 1, "");
        }
        startTime = System.currentTimeMillis();
    }

    public synchronized void setEndTime() {
        if (null != endTime) {
            throw new TaskContextException(TaskContextException.CODE0 + 2, "");
        }
        endTime = System.currentTimeMillis();
    }

}
